"""
处理 filelist 文件：
1 删除为空的文件
2 删除有问题的文件
"""

import sys
import os
import traceback
from PIL import Image
from my_py_toolkit.file.file_toolkit import read_file, write_file
from my_py_toolkit.decorator.multi_thread_decorator import multi_thread
import argparse

parser = argparse.ArgumentParser(description='handle filelist')
parser.add_argument('filelist_path', type=str, help='filelist_path')
parser.add_argument('--save_path', required=False, type=str, default='', help='结果保存路径')
args = parser.parse_args()
if not args.save_path:
    args.save_path = args.filelist_path + '.handled_multi_thread'

def remove_empty_file(filelist):
    result = []
    for file in filelist:
        if os.stat(file).st_size > 0:
            result.append(file)
    return result

def handle_filelist(filelist_file, save_path=None):
    if not save_path:
        save_path = filelist_file + '.handled'

    filelist = read_file(filelist_file, '\n')
    filelist = remove_empty_file(filelist)
    write_file('\n'.join(filelist), save_path)

def handle(filepath):
    try:
        if os.stat(filepath).st_size == 0:
            return
        
        Image.open(filepath).convert('RGB')
        
        return filepath
    except Exception:
        print(f'Error: {filepath}, \n{traceback.format_exc()}')
        return


def handle_one():
    # 单线程
    save_path = None
    cts = 0
    filelist = sys.argv[1]
    if len(sys.argv) > 2:
        save_path = sys.argv[1]
    if not save_path:
        save_path = filelist + '.handled_single_thread'
    
    writer = open(save_path, 'w', encoding='utf-8')

    with open(filelist, 'r', encoding='utf-8') as reader:
        line = reader.readline()
        while line:
            cts += 1
            line = line.strip('\n')
            line = handle(line)
            if line:
                writer.write(line + '\n')
            
            print(f'handle nums: {cts}')
            line = reader.readline()

@multi_thread(logger=None, res_path=args.save_path)
def handle_filelist(filelist):
    result = []
    for filepath in filelist:
        try:
            if not filepath:
                continue

            if os.stat(filepath).st_size == 0:
                continue
            Image.open(filepath).convert('RGB')

            result.append(filepath)
            
        except Exception:
            print(f'Error: {filepath}, \n{traceback.format_exc()}')
            continue
    
    if len(result) == 1:
        result = result[0]
    return result

def handle_multi():
    handle_filelist(args.filelist_path)

if __name__ == '__main__':
    handle_multi()

    

    # handle_filelist(filelist, save_path)l